const app = getApp()
import { getTeamMember, getMyJoinTeam, postDeleteMember } from '../../../../api/index'

Page({
  data: {
    tabActive: 'my',
    members: [],
    teamList: [],
    refresher: false
  },
  async onRefresh () {
    await this.getRequest()
    this.setData({ refresher: false })
  },
  seeTeam ({ currentTarget: { dataset: { item } } }) {
    wx.$nav.navigateTo(`/pages/account/team/member/index?id=${item.teamId}`)
  },
  async delMember ({ currentTarget: { dataset: { item } } }) {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '删除成员', content: '确定要删除该成员吗？' })
      if (confirm) {
        wx.$pro.showLoading({ title: '删除中...', mask: true })
        await postDeleteMember({ userId: item.userId })
        wx.$pro.hideLoading()
        wx.showToast({ title: '删除成功！', icon: 'none' })
        this.getRequest()
      }
    } catch (err) {
      wx.$pro.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  inviteMember () {
    wx.$nav.navigateTo(`/pages/account/team/invite/index`)
  },
  changeTab ({ currentTarget: { dataset: { value } } }) {
    if (value !== this.data.tabActive) {
      this.setData({ tabActive: value })
      this.getRequest()
    }
  },
  async getMyList () {
    try {
      wx.$pro.showLoading({ title: '加载中...', mask: true})
      const { ResultSet } = await getTeamMember()
      this.setData({ members: ResultSet.userData.teamMembers })
      wx.$pro.hideLoading()
    } catch (err) {
      wx.$pro.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getJoinList () {
    try {
      wx.$pro.showLoading({ title: '加载中...', mask: true})
      const { ResultSet } = await getMyJoinTeam()
      this.setData({ teamList: ResultSet.userData.teamInfo })
      wx.$pro.hideLoading()
    } catch (err) {
      wx.$pro.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  getRequest () {
    if (this.data.tabActive === 'my') this.getMyList()
    else this.getJoinList()
  },
  onShow () {
    this.getRequest()
  }
})